package com.joyance.springmvc.util.json;

import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;

public class JsonStringUtil {

	@SuppressWarnings({ "rawtypes", "unchecked" })
	public static String jsonStringFirstCodeReplace(String str) {
		if (str == null || "".equals(str.trim())) {
			return null;
		}
		String ret = null;
		try {
			Object value = null;
			if (str.startsWith("[") && str.endsWith("]")) {
				Map[] maps = JsonUtils.readObject(str, Map[].class);
				if (maps == null) {
					return null;
				}
				int length = maps.length;
				for (int i = 0; i < length; i++) {
					maps[i] = parseMap(maps[i]);
				}
				value = maps;
			} else {
				Map map = JsonUtils.readObject(str, Map.class);
				if (map == null) {
					return null;
				}
				value = parseMap(map);
			}
			if (value != null) {
				ret = JsonUtils.writeObject(value);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return ret;
	}

	@SuppressWarnings("unchecked")
	private static Map<String, Object> parseMap(Map<String, Object> map) {
		if (map == null) {
			return null;
		}
		Set<String> set = map.keySet();
		Map<String, Object> ret = new LinkedHashMap<String, Object>();
		for (String key : set) {
			if (key == null || "".equals(key.trim())) {
				continue;
			}
			String newKey = null;
			if (key.equals(key.toUpperCase())) {// 判断是否全是大写字母，如果是，全部改为小写
				newKey = key.toLowerCase();
			} else {
				char firstCode = key.charAt(0);// 将首字母从大写改为小写
				String firstStr = String.valueOf(firstCode);
				if (firstStr == null) {
					continue;
				}
				newKey = key.replaceFirst(firstStr, firstStr.toLowerCase());
			}
			Object value = map.get(key);
			if (value != null && value instanceof Map) {
				Map<String, Object> childMap = (Map<String, Object>) value;
				value = parseMap(childMap);
			}

			ret.put(newKey, value);
		}
		return ret;
	}

	public static void main(String[] args) {
		long t1 = System.currentTimeMillis();
		for (int i = 0; i < 1000; i++) {
			String json = "{\"key\":\"yy\",\"a\":{\"key\":\"uuu\",\"a\":null,\"IDE\":10},\"IDE\":100}";
			jsonStringFirstCodeReplace(json);

			json = "[{\"Key\":\"yy\",\"A\":{\"Key\":\"uuu\",\"A\":null,\"IDE\":10},\"IDE\":100},{\"Key\":\"uuu\",\"A\":null,\"IDE\":10}]";
			jsonStringFirstCodeReplace(json);
		}
		long t2 = System.currentTimeMillis();
		System.out.println(t2 - t1);
	}
}
